import React, { useRef } from 'react';
import { StyleSheet } from 'react-native';
import { GestureDetector, Gesture, GestureHandlerRootView } from 'react-native-gesture-handler';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, runOnJS } from 'react-native-reanimated';

const ZoomableVector = ({ children, minScale = 0.5, maxScale = 3 }) => {
  const scale = useSharedValue(1);
  const translateX = useSharedValue(0);
  const translateY = useSharedValue(0);
  const lastScale = useRef(1);
  const lastTranslateX = useRef(0);
  const lastTranslateY = useRef(0);

  const animatedStyle = useAnimatedStyle(() => {
    return {
      transform: [
        { translateX: translateX.value },
        { translateY: translateY.value },
        { scale: scale.value },
      ],
    };
  });

  const pinchGesture = Gesture.Pinch()
    .onBegin(() => {
      // 在开始缩放时更新lastScale值
      lastScale.current = scale.value;
    })
    .onUpdate((event) => {
      scale.value = lastScale.current * event.scale;
      // 限制缩放范围
      if (scale.value < minScale) {
        scale.value = minScale;
      } else if (scale.value > maxScale) {
        scale.value = maxScale;
      }
    })
    .onEnd(() => {
      lastScale.current = scale.value;
    });

  const panGesture = Gesture.Pan()
    .enabled(scale.value > 1) // 只有在放大时才允许平移
    .onBegin(() => {
      // 在开始平移时更新lastTranslate值
      lastTranslateX.current = translateX.value;
      lastTranslateY.current = translateY.value;
    })
    .onUpdate((event) => {
      translateX.value = lastTranslateX.current + event.translationX;
      translateY.value = lastTranslateY.current + event.translationY;
    })
    .onEnd(() => {
      lastTranslateX.current = translateX.value;
      lastTranslateY.current = translateY.value;
    });

  const doubleTapGesture = Gesture.Tap()
    .numberOfTaps(2)
    .onEnd(() => {
      // 双击重置
      scale.value = withTiming(1);
      translateX.value = withTiming(0);
      translateY.value = withTiming(0);
      lastScale.current = 1;
      lastTranslateX.current = 0;
      lastTranslateY.current = 0;
    });

  const composedGesture = Gesture.Race(pinchGesture, panGesture, doubleTapGesture);

  return (
    <GestureHandlerRootView style={styles.container}>
      <GestureDetector gesture={composedGesture}>
        <Animated.View style={[styles.content, animatedStyle]}>
          {children}
        </Animated.View>
      </GestureDetector>
    </GestureHandlerRootView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default ZoomableVector;